<template>
  <div class="dashboard">
    <div class="filter-section">
      <el-form :inline="true">
        <el-form-item style="margin-bottom: 0">
          <el-select v-model="timeRange" @change="handleTimeRangeChange">
            <el-option label="最近7天" value="7" />
            <el-option label="最近30天" value="30" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="timeRange === 'custom'" style="margin-bottom: 0">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            @change="handleDateRangeChange"
          />
        </el-form-item>
      </el-form>
    </div>

    <div class="home">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="mb-4">
            <div slot="header">访问国家占比</div>
            <v-chart class="chart" :option="visitCountryOption" autoresize />
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="mb-4">
            <div slot="header">下单国家占比</div>
            <v-chart class="chart" :option="orderCountryOption" autoresize />
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="mb-4">
            <div slot="header">代理商与散客订单量占比</div>
            <v-chart class="chart" :option="userTypeOption" autoresize />
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <div slot="header">每日访问量</div>
            <v-chart class="chart" :option="dailyVisitOption" autoresize />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">每日下单量</div>
            <v-chart class="chart" :option="dailyOrderOption" autoresize />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from 'echarts/components'
import { http } from '@/api'

use([
  CanvasRenderer,
  PieChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
])

export default {
  name: 'Dashboard',
  components: {
    VChart
  },
  data() {
    return {
      timeRange: '7',
      dateRange: null,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      visitCountryOption: {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        series: [{
          type: 'pie',
          radius: '55%',
          data: []
        }]
      },
      orderCountryOption: {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        series: [{
          type: 'pie',
          radius: '55%',
          data: []
        }]
      },
      userTypeOption: {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        series: [{
          type: 'pie',
          radius: '55%',
          data: []
        }]
      },
      dailyVisitOption: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: 40,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#409EFF'
          },
          label: {
            show: true,
            position: 'top'
          },
          barMaxWidth: 30
        }]
      },
      dailyOrderOption: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: 40,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#67C23A'
          },
          barMaxWidth: 30,
          label: {
            show: true,
            position: 'top'
          }
        }]
      }
    }
  },
  methods: {
    handleTimeRangeChange(value) {
      if (value !== 'custom') {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * parseInt(value))
        this.dateRange = [
          this.formatDate(start),
          this.formatDate(end)
        ]
        this.fetchData()
      }
    },
    handleDateRangeChange() {
      if (this.dateRange) {
        this.fetchData()
      }
    },
    formatDate(date) {
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    async fetchData() {
      try {
        const params = {
          start_time: this.dateRange[0],
          end_time: this.dateRange[1]
        }
        const response = await http.statistics.dashboard(params)
        const data = response.data

        // 更新访问国家占比
        this.visitCountryOption.series[0].data = data.countryList

        // 更新下单国家占比
        this.orderCountryOption.series[0].data = data.userCountryList

        // 更新用户类型占比
        this.userTypeOption.series[0].data = data.compareList

        // 更新每日访问量
        this.dailyVisitOption.xAxis.data = data.dateList.map(item => item.name)
        this.dailyVisitOption.series[0].data = data.dateList.map(item => item.value)

        // 更新每日下单量
        this.dailyOrderOption.xAxis.data = data.orderDateList.map(item => item.name)
        this.dailyOrderOption.series[0].data = data.orderDateList.map(item => item.value)
      } catch (error) {
        console.error('Failed to fetch dashboard data:', error)
        this.$message.error('获取数据失败')
      }
    }
  },
  mounted() {
    this.handleTimeRangeChange('7') // 默认显示最近7天
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  height: 90vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  .filter-section {
    margin-bottom: 20px;
    flex-shrink: 0;
  }

  .home {
    flex: 1;
    overflow-y: auto;
    min-height: 0;

    .mb-4 {
      margin-bottom: 16px;
    }

    .el-card {
      height: 100%;
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .chart {
      height: 300px;
    }

    .el-row {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
